package com.onlyphoto.onlymall.mvp.view.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.ViewPager
import cn.jpush.android.api.JPushInterface
import com.nineoldandroids.view.ViewHelper
import com.onlyphoto.onlymall.base.BaseActivity
import com.onlyphoto.onlymall.R
import com.onlyphoto.onlymall.events.ChangeToSmsLoginEvent
import com.onlyphoto.onlymall.events.LoginEvent
import com.onlyphoto.onlymall.interfaces.PhoneCallback
import com.onlyphoto.onlymall.mvp.contract.CLogin
import com.onlyphoto.onlymall.mvp.presenter.PLoginImpl
import com.onlyphoto.onlymall.mvp.view.fragment.LoginByPwdFragment
import com.onlyphoto.onlymall.mvp.view.fragment.LoginBySmsFragment
import com.onlyphoto.onlymall.utils.*
import kotlinx.android.synthetic.main.activity_login.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import com.google.gson.Gson
import com.onlyphoto.onlymall.bean.response.UserInfoBean


/**
 * 此类的代码还需要删减
 */

class LoginActivity : BaseActivity<PLoginImpl>(), CLogin.IVLogin, PhoneCallback, View.OnClickListener {

    private var currentItem = 0

    private var adapter: FragmentAdapter? = null

    companion object {
        var phoneNum: String? = ""
        private val TAG_CURRENT_ITEM = "tag_current_item"

        /**
         * 获取跳转Intent
         *
         * @param context     上下文
         * @param currentItem 滑块选中的位置设置
         * @return Intent
         */
        fun makeIntent(context: Context, currentItem: Int): Intent {
            val intent = Intent(context, LoginActivity::class.java)
            intent.putExtra(TAG_CURRENT_ITEM, currentItem)
            return intent
        }

        fun makeIntent(context: Context, phone: String): Intent {
            phoneNum = phone
            return makeIntent(context, 0)
        }

        fun makeIntent(context: Context, phone: String, currentItem: Int): Intent {
            phoneNum = phone
            return makeIntent(context, currentItem)
        }
    }

    override fun retry() {}

    override fun init() {
        if (TextUtils.isEmpty(phoneNum)) {
            val phone = SharePreferenceUtil.getInstance(this).getData(Constants.SHARE_TAG_LOGIN_PHONE).trim()

            if (!StringUtil.isBlank(phone) && StringUtil.isMobileNO(phone)) {
                phoneNum = phone
            }
        }

        if (intent != null) {
            currentItem = intent.getIntExtra(TAG_CURRENT_ITEM, 0)
        }

        //初始化viewpager
        adapter = FragmentAdapter(supportFragmentManager)
        login_view_pager.adapter = adapter

        login_tab_layout.setupWithViewPager(login_view_pager)

        login_view_pager.currentItem = currentItem
    }

    override fun initListener() {
        //点击事件初始化
        login_view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                //计算方法: 偏移比例（positionOffset）* 每份的宽度 + position对应的偏移宽度 + 初始偏移宽度
                val itemCount = login_view_pager.adapter?.count
                //每个等分的宽度
                val eachWidth = ConvertUtil.getScreenWidth(this@LoginActivity) / itemCount!!
                val initOffsetPixels = (eachWidth / 2) - (ConvertUtil.dp2px(this@LoginActivity, 20f) / 2)
                ViewHelper.setTranslationX(tab_indicator,
                        (eachWidth * positionOffset + eachWidth * position ) + initOffsetPixels)
            }

            override fun onPageSelected(position: Int) {
                AndroidUtils.hideSoftInput(this@LoginActivity)
            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        })

        back.setOnClickListener(this)
        login_by_wechat.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.back -> finish()
            R.id.login_by_wechat -> wechatLogin()
        }
    }

    private fun wechatLogin() {
        //友盟授权第三方登录
    }

    override fun wxLoginSuccess(bean: UserInfoBean) {
        UserUtil.saveUserInfo(this, bean)
        JPushInterface.setAlias(this@LoginActivity, 1, bean.user_alias)
        SharePreferenceUtil.getInstance(this).setBoolData(Constants.IS_PHONE_LOGIN, false)
        finish()
    }

    override fun showToast(msg: String) {
        ToastUtil.showToast(msg)
    }

    override fun loadData() {

    }

    override fun isFullScreen(): Boolean {
        //是否沉浸式， 默认非沉浸式
        return false
    }

    public override fun initCustomerStatusManager() {

    }

    override fun setContentViewId(): Int {
        return R.layout.activity_login
    }

    override fun createPresenter() {
        mPresenter = PLoginImpl(mContext, this)
    }

    override fun showLoading() {
        showDefaultDialog()
    }

    override fun hideLoading() {
        hideDefaultDialog()
    }
    override fun phoneCange(newPhone: String) {
        phoneNum = newPhone
    }


    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    fun onLoingEvent(event: LoginEvent) {
        handleSuccessJump(event.context!!)
        finish()
    }


    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    fun onMessageEvent(event: ChangeToSmsLoginEvent) {
        login_tab_layout.getTabAt(0)?.select()
    }


    /**
     * 处理登录成功之后的跳转
     */
    private fun handleSuccessJump(context: Context) {
        if (intent == null || TextUtils.isEmpty(getIntent().getStringExtra("url"))) {
            return
        }
        val intent = Intent()
        try {
            intent.setClass(context, Class.forName(getIntent().getStringExtra("url")))
            startActivity(intent)
        } catch (e: ClassNotFoundException) {
            e.printStackTrace()
        }
    }

    override fun doWhenLoginInvalid() {
        LogUtil.log("LoginActivity", "login not do")
    }

    override fun onDestroy() {
        phoneNum = ""
        super.onDestroy()
    }


    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        init()
    }

    /**
     * ViewPager 适配器
     */
    private class FragmentAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) {

        private val title = arrayOf("快捷登录", "账号密码登录")


        override fun getItem(position: Int): Fragment {
            val fragment: Fragment?

            if (0 == position) {
                fragment = LoginBySmsFragment()

            } else {
                fragment = LoginByPwdFragment()
            }
            val bundle = Bundle()
            bundle.putString("phone", phoneNum)
            fragment.arguments = bundle
            return fragment
        }

        override fun getCount(): Int {
            return title.size
        }

        override fun getPageTitle(position: Int): CharSequence {
            return title[position]
        }
    }

}
